#include "fewidgetfactory_private.h"
#include <QLabel>
#include <QPushButton>

FeSystemWidgetFactory::FeSystemWidgetFactory(QObject *parent)
{
	// register built-in widget types
	wfs.insert("qt.label", this);
	wfs.insert("qt.pushbutton", this);
}

FeSystemWidgetFactory::~FeSystemWidgetFactory()
{
}

QStringList FeSystemWidgetFactory::supportedWidgetTypes() const
{
	return wfs.keys();
}

QWidget *FeSystemWidgetFactory::createBuiltInWidget(const QString &type, QWidget *parent)
{
	QWidget *w = 0;
	if(type == "qt.label")
	{
		w = new QLabel;
	}
	else if(type == "qt.pushbutton")
	{
		w = new QPushButton;
		w->setSizePolicy(
			QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum));
	}
	return w;
}

QWidget *FeSystemWidgetFactory::createWidget(const QString &type, QWidget *parent)
{
	QWidget *w = 0;
	QMap<QString, FeWidgetFactory *>::const_iterator i =
		wfs.find(type);
	if(i != wfs.end())
	{
		if(i.value() == this)
		{
			w = createBuiltInWidget(type, parent);
		}
		else
		{
			w = i.value()->createWidget(type, parent);
		}
	}

	return w;
}

void FeSystemWidgetFactory::registerWidgetFactory(FeWidgetFactory *factory)
{
	Q_ASSERT(factory && factory != this);
	const QStringList types = factory->supportedWidgetTypes();
	for(QStringList::const_iterator i = types.begin(); i != types.end(); ++i)
	{
		const QString &type = *i;
		if(!wfs.contains(type))
		{
			wfs.insert(type, factory);
		}
		else
		{
			QByteArray type_name = type.toLatin1();
			qWarning("Widget factory for type %s already registred",
				type_name.constData());
		}
	}
}

void FeSystemWidgetFactory::unregisterWidgetFactory(FeWidgetFactory *factory)
{
	Q_ASSERT(factory && factory != this);
	QMap<QString, FeWidgetFactory *>::iterator i = wfs.begin();
	while(i != wfs.end())
	{
		if(i.value() == factory)
		{
			i = wfs.erase(i);
		}
		else
		{
			++i;
		}
	}
}